package com.jk.controller.account;

import com.jk.dto.JsonResult;
import com.jk.dto.account.AccThemeDTO;
import com.jk.entity.account.AccTheme;
import com.jk.service.account.AccThemeService;
import com.jk.util.BeanMapper;
import com.jk.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *  Created by yanghuan on 15-8-31.
 */
@Controller
@RequestMapping("/account/theme")
public class ThemeController {

    @Autowired
    private AccThemeService accThemeService;

    //跳转到角色管理页面
    @RequestMapping("/page")
    public String manage() {
        return "account/theme";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public String save(AccThemeDTO accThemeDTO, HttpServletRequest request) {
        try {
            AccTheme accTheme = BeanMapper.map(accThemeDTO, AccTheme.class);
            accThemeService.save(accTheme);
            request.getSession().setAttribute("accTheme", accTheme);
            return JsonUtil.toString(new JsonResult(200, "保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.toString(new JsonResult(201, "保存失败"));
        }
    }

    @RequestMapping(value = "/upload")
    @ResponseBody
    public void upload(@RequestParam("uploadFile") CommonsMultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter pw = response.getWriter();
        response.setHeader("Content-Type", "text/html");//不加的话前端输出字符串会带上<pre>标签
        //保存
        try {
            String path = request.getSession().getServletContext().getRealPath("/static/images/logo.png");
            File targetFile = new File(path);
            if (!targetFile.exists()) {
                targetFile.delete();
            }
            file.transferTo(targetFile);
            pw.print(JsonUtil.toString(new JsonResult(200, "上传成功")));
        } catch (Exception e) {
            e.printStackTrace();
            pw.print(JsonUtil.toString(new JsonResult(201, "上传失败")));
        } finally {
            pw.flush();
            pw.close();
        }
    }
}
